# -*- coding: utf-8 -*-

import os
import sys
import datetime
import pytz
import jinja2
from openerp.http import request
from openerp.exceptions import ValidationError
from openerp.osv import osv

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package
    # loader.
    path = os.path.realpath(os.path.join(
        os.path.dirname(__file__), '..', 'views'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_lodop', "report")

env = jinja2.Environment(loader=loader, autoescape=True)


def strftime(str, fmt):
    dt = datetime.datetime.strptime(str, '%Y-%m-%d %H:%M:%S')
    dt = dt.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
    return dt.strftime(fmt.encode('utf-8')).decode('utf-8')

env.filters['strftime'] = strftime

# render采分批采购订单打印模板
class report_purchase_order_lodop(osv.AbstractModel):
    """Model used to embed lodop reports"""
    _name = 'report.stock_report_picking_purchase_ext'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        model = 'stock.picking'
        report_obj = self.pool[model]
        stock_picking = report_obj.browse(cr, uid, ids, context=context)

        curUser = self.pool.get('res.users').browse(cr,uid,uid,context=None)
        template = env.get_template("purchase_stock_picking_print.html")

        return template.render({
            'stock_picking': stock_picking,
            'curUser': curUser
            })

class report_stock_picking_lodop(osv.AbstractModel):
    """Model used to embed lodop reports"""
    _name = 'report.stock_report_picking_ext'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        model = 'stock.picking'
        report_obj = self.pool[model]
        picking = report_obj.browse(cr, uid, ids, context=context)
        template = env.get_template("stock_picking_print.html")
        if not picking.so_id:
            return template.render({
                'warning': True,
            })
            # 先取到出货单对应的订单id，再去取得订单的对象
            # order_id = self.pool.get('sale.order').search(
            #     cr, uid, picking.so_id, context=context)
        else:
            order = self.pool.get('sale.order').browse(
                cr, uid, picking.so_id.id, context=None)
            curUser = self.pool.get('res.users').browse(
                cr, uid, uid, context=None)

            chinese = {'0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆',
                       '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖'}
            price = {}
            for order_line in order.order_line:
                price.update({str(order_line.product_id.id): order_line.price_unit})
            amount_total = 0
            for piking_line in picking.move_lines:
                amount_total += round(price.get(str(piking_line.product_id.id))
                                      * piking_line.product_uom_qty, 1)
            picking.write({'print_state': True})
            # 取得纸质发票个数
            official_invoice_map = {} #{False: 1L, True: 1L}
            if order.sale_order_invoice:
                cr.execute("SELECT is_outer_invoice, COUNT(*) as invoice_count FROM official_invoice_lines WHERE official_invoice_id=%s GROUP BY is_outer_invoice", (order.sale_order_invoice.id, ))
                official_invoiced_line = cr.dictfetchall()
                for invoiced_line in official_invoiced_line:
                    official_invoice_map[invoiced_line.get('is_outer_invoice')] = invoiced_line.get('invoice_count')

            #模板渲染
            return template.render({
                'picking': picking,
                'order': order,
                'curUser': curUser,
                'debug': context,
                'chinese': chinese,
                'price': price,
                'amount_total': amount_total,
                'warning': False,
                'official_invoice_map': official_invoice_map
            })

# 新A4纸出货单
class report_stock_new_picking_out(osv.AbstractModel):
    """Model used to embed lodop reports"""
    _name = 'report.stock_report_new_picking_out'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        model = 'stock.picking'
        report_obj = self.pool[model]
        picking = report_obj.browse(cr, uid, ids, context=context)

        sale_order_model_name = 'sale.order'
        sale_order_obj = self.pool[sale_order_model_name]
        order = sale_order_obj.browse(cr, uid, picking.so_id, context=context)
        fake_order = None
        # 如果是假单
        if order.real_so_id:
            fake_order = order
            order = sale_order_obj.browse(cr, uid, order.real_so_id.id, context=context)
        else:
            fake_order_id = sale_order_obj.search(cr, uid, [('real_so_id', '=', order.id)], context=context)
            if fake_order_id:
                fake_order = sale_order_obj.browse(cr, uid, fake_order_id, context=context)

        if not fake_order:
            raise Exception(u"没有假单")
        # picking_row_id = self.pool["stock.picking"].search(cr, uid, [('so_id', '=', order.id)], context=context)
        # picking_row = None
        # if picking_row_id:
        #     picking_row = self.pool["stock.picking"].browse(cr, uid, picking_row_id[0], context=context)
        # else:
        #     self.pool["sale.order"].create_out_going_picking(cr, uid, order.id, context=context)
        #     picking_row_id = self.pool["stock.picking"].search(cr, uid, [('so_id', '=', order.id)], context=context)
        #     picking_row = self.pool["stock.picking"].browse(cr, uid, picking_row_id[0], context=context)

        template = env.get_template("stock_report_new_picking_out.html")
        options = data or {}

        # 取得纸质发票个数
        official_invoice_map = {}  # {False: 1L, True: 1L}
        if order.sale_order_invoice:
            cr.execute(
                "SELECT is_outer_invoice, COUNT(*) as invoice_count FROM official_invoice_lines WHERE official_invoice_id=%s GROUP BY is_outer_invoice",
                (order.sale_order_invoice.id,))
            official_invoiced_line = cr.dictfetchall()
            for invoiced_line in official_invoiced_line:
                official_invoice_map[invoiced_line.get('is_outer_invoice')] = invoiced_line.get('invoice_count')
        # 当前用户
        curUser = self.pool.get('res.users').browse(
            cr, uid, uid, context=None)
        # 只打印一张的时候，也就是非批量打印的时候才设置已打印状态
        # 测试期间暂时不修改打印状态
        # if len(ids) == 1:
        #    order.write({'is_tallying_printed': True})
        chinese = {'0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆',
                   '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖'}

        url_prefix = "http://" + request.httprequest.host
        lodop_host = '192.168.0.10'
        if url_prefix.find('localhost') > 0 or url_prefix.find('tunnel') > 0:
            lodop_host = '127.0.0.1'

        shanghai_now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        return template.render({
            'sale_order': order,
            'fake_order': fake_order,
            'ids': ids,
            'curUser': curUser,
            'debug': context,
            'chinese': chinese,
            'warning': False,
            'options': options,
            'official_invoice_map': official_invoice_map,
            'url_prefix': url_prefix,
            'shanghai_now_time': shanghai_now_time,
            'lodop_host': lodop_host,
            # 'picking_row': picking_row
        })
